﻿/*************************************************************************************
 * 文 件 名:   HK_SimpleQuizCtrl
 * 
 * 描    述:   建议题库模块的总控脚本
 * 
 * 版    本：  V1.0
 * 创 建 者：  京产肠饭
 * 创建时间：  2021/11/18
 * 链   接：  https://gitee.com/JingChanChangFan/hk_-unity-tools
*************************************************************************************/

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using QFramework;

namespace HKTools
{
    public class HK_UI_SimpleQuizPanel : MonoBehaviour, IController
    {
        public IArchitecture GetArchitecture()
        {
            // 根据每个项目应用的框架进行修改
            return HKSimpleQuiz_Architecture.Interface;
        }

        public Toggle single_Toggle;
        public Toggle multiple_Toggle;
        public Toggle trueFalse_Toggle;
        public Toggle blank_Toggle;
        public Toggle shortAnswer_Toggle;

        [Header("单选题预设体")]
        public HK_SingleChoiceItem singleItem_Prefab;
        [Header("多选题预设体")]
        public HK_MultipleChoiceItem multipleItem_Prefab;
        [Header("判断题预设体")]
        public HK_TrueFalseItem trueFalseItem_Prefab;
        [Header("填空题预设体")]
        public HK_BlankItem blankItem_Prefab;
        [Header("简答题预设体")]
        public HK_ShortAnswerItem shortAnswerItem_Prefab;

        [Header("题目的父物体")]
        public GameObject singleChoicePanel;
        public RectTransform singleChoiceContent;
        GridLayoutGroup singleChoiceGrid;

        public GameObject multipleChoicePanel;
        public RectTransform multipleChoiceContent;
        GridLayoutGroup multipleChoiceGrid;

        public GameObject trueFalsePanel;
        public RectTransform trueFalseContent;
        GridLayoutGroup trueFalseGrid;

        public GameObject blankPanel;
        public RectTransform blankContent;
        GridLayoutGroup blankGrid;

        public GameObject shortAnswerPanel;
        public RectTransform shortAnswerContent;
        GridLayoutGroup shortAnswerGrid;

        List<GameObject> quesPanel_List = new List<GameObject>();

        // 单选题、多选题集合
        List<HK_SingleChoiceItem> allSingle_List = new List<HK_SingleChoiceItem>();
        List<HK_MultipleChoiceItem> allMultiple_List = new List<HK_MultipleChoiceItem>();
        List<HK_TrueFalseItem> allTrueFalse_List = new List<HK_TrueFalseItem>();
        List<HK_BlankItem> allBlank_List = new List<HK_BlankItem>();
        List<HK_ShortAnswerItem> allShortAnswer_List = new List<HK_ShortAnswerItem>();

        [Header("提交按钮：")]
        public Button Submit_Btn;

        [Header("提示面板及其内容：")]
        public GameObject tipsPanel_Go;
        public Text tips_Text;
        public Button left_Btn;
        public Button right_Btn;

        public HK_UI_QuizTipsPanel quizTipsPanel;
        bool isAllQuesComplete;

        IHK_QuesDataModel quesDataModel;

        int singleDone_Num = 0;
        int multipleDone_Num = 0;
        int trueFalseDone_Num = 0;
        int blankDone_Num = 0;
        int shortAnswer_Num = 0;

        void Awake()
        {
            // 注册 题目UI面板初始化事件
            this.RegisterEvent<HK_InitQuesItems_Event>(arg =>
            {
                OnInitQuesItems();
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            // 注册 展示错题事件
            this.RegisterEvent<HK_ShowWrongQuesItem>(arg =>
            {
                OnShowWrongQuesItem();
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            // 注册 答题完成事件
            this.RegisterEvent<HK_QuizComplete_Event>(arg =>
            {
                Debug.Log("答题完成!");
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            // 注册 放弃答题事件
            this.RegisterEvent<HK_QuizGiveUp_Event>(arg =>
            {
                Debug.Log("放弃答题！");
            }).UnRegisterWhenGameObjectDestroyed(gameObject);

            quesPanel_List.Add(singleChoicePanel);
            quesPanel_List.Add(multipleChoicePanel);
            quesPanel_List.Add(trueFalsePanel);
            quesPanel_List.Add(blankPanel);
            quesPanel_List.Add(shortAnswerPanel);

            single_Toggle.onValueChanged.AddListener(OnSingleToggleChanged);
            multiple_Toggle.onValueChanged.AddListener(onMultipleToggleChanged);
            trueFalse_Toggle.onValueChanged.AddListener(OnTrueFalseToggleChanged);
            blank_Toggle.onValueChanged.AddListener(OnBlankToggleChanged);
            shortAnswer_Toggle.onValueChanged.AddListener(OnShortAnswerToggleChanged);

            singleChoiceGrid = singleChoiceContent.GetComponent<GridLayoutGroup>();
            multipleChoiceGrid = multipleChoiceContent.GetComponent<GridLayoutGroup>();
            trueFalseGrid = trueFalseContent.GetComponent<GridLayoutGroup>();
            blankGrid = blankContent.GetComponent<GridLayoutGroup>();
            shortAnswerGrid = shortAnswerContent.GetComponent<GridLayoutGroup>();

            quesDataModel = this.GetModel<IHK_QuesDataModel>();
            Submit_Btn.onClick.AddListener(OnClickSubmitBtn);
        }

        void Update()
        {
            #region 测试-初始化题库面板
            if (Input.GetKeyDown(KeyCode.F1))
            {
                string path = Application.dataPath + "/HKTools/ForRuntime/HK_SimpleQuiz/QuestionDataExp_01.json";
                InitFromJson(path);
            }
            #endregion

            // 点击鼠标左键的时候，判断当前类型题做的进度
            if (Input.GetMouseButtonDown(0) || Input.GetMouseButtonUp(0))
                JudgeSubjectDoneProgress();
        }

        /// <summary>
        /// 通过 Json 初始化题库面板
        /// </summary>
        public void InitFromJson(string filePath)
        {
            this.GetSystem<IHK_QuesDataSystem>().GetQuesDataFromJson(filePath);
        }

        /// <summary>
        /// 通过 Excel 初始化题库面板
        /// </summary>
        public void InitFromExcel(string filePath)
        {
            this.GetSystem<IHK_QuesDataSystem>().GetQuesDataFromExcel(filePath);
        }

        // 初始化题库面板
        void OnInitQuesItems()
        {
            Submit_Btn.gameObject.SetActive(true);

            singleChoiceGrid.cellSize = new Vector2(1000, 430);
            multipleChoiceGrid.cellSize = new Vector2(1000, 430);
            trueFalseGrid.cellSize = new Vector2(1000, 200);
            blankGrid.cellSize = new Vector2(1000, 200);
            shortAnswerGrid.cellSize = new Vector2(1000, 350);

            single_Toggle.GetComponentInChildren<Text>().text = "单选题(0/" + quesDataModel.Single_Num.Value.ToString() + ")";
            multiple_Toggle.GetComponentInChildren<Text>().text = "多选题(0/" + quesDataModel.Multiple_Num.Value.ToString() + ")";
            trueFalse_Toggle.GetComponentInChildren<Text>().text = "判断题(0/" + quesDataModel.TrueFalse_Num.Value.ToString() + ")";
            blank_Toggle.GetComponentInChildren<Text>().text = "填空题(0/" + quesDataModel.Blank_Num.Value.ToString() + ")";
            shortAnswer_Toggle.GetComponentInChildren<Text>().text = "简答题(0/" + quesDataModel.ShortAnswer_Num.Value.ToString() + ")";

            for (int i = 0; i < allSingle_List.Count; i++)
                Destroy(allSingle_List[i].gameObject);

            allSingle_List.Clear();

            for (int i = 0; i < allMultiple_List.Count; i++)
                Destroy(allMultiple_List[i].gameObject);

            allMultiple_List.Clear();

            for (int i = 0; i < allTrueFalse_List.Count; i++)
                Destroy(allTrueFalse_List[i].gameObject);

            allTrueFalse_List.Clear();

            for (int i = 0; i < allBlank_List.Count; i++)
                Destroy(allBlank_List[i].gameObject);

            allBlank_List.Clear();

            for (int i = 0; i < allShortAnswer_List.Count; i++)
                Destroy(allShortAnswer_List[i].gameObject);

            allShortAnswer_List.Clear();


            for (int i = 0; i < quesDataModel.Single_Num.Value; i++)
            {
                HK_SingleChoiceItem item = Instantiate(singleItem_Prefab, singleChoiceContent);
                item.InitQuesItem(quesDataModel.QuizData.Value.SingleChoice_List[i], i + 1);
                allSingle_List.Add(item);
            }

            for (int i = 0; i < quesDataModel.Multiple_Num.Value; i++)
            {
                HK_MultipleChoiceItem item = Instantiate(multipleItem_Prefab, multipleChoiceContent);
                item.InitQuesItem(quesDataModel.QuizData.Value.MultipleChoice_List[i], i + 1);
                allMultiple_List.Add(item);
            }

            for (int i = 0; i < quesDataModel.TrueFalse_Num.Value; i++)
            {
                HK_TrueFalseItem item = Instantiate(trueFalseItem_Prefab, trueFalseContent);
                item.InitQuesItem(quesDataModel.QuizData.Value.TrueFalse_List[i], i + 1);
                allTrueFalse_List.Add(item);
            }

            for (int i = 0; i < quesDataModel.Blank_Num.Value; i++)
            {
                HK_BlankItem item = Instantiate(blankItem_Prefab, blankContent);
                item.InitQuesItem(quesDataModel.QuizData.Value.Blank_List[i], i + 1);
                allBlank_List.Add(item);
            }

            for (int i = 0; i < quesDataModel.ShortAnswer_Num.Value; i++)
            {
                HK_ShortAnswerItem item = Instantiate(shortAnswerItem_Prefab, shortAnswerContent);
                item.InitQuesItem(quesDataModel.QuizData.Value.ShortAnswer_List[i], i + 1);
                allShortAnswer_List.Add(item);
            }

            OnSingleToggleChanged(true);
        }

        void OnSingleToggleChanged(bool isOn)
        {
            if (!isOn)
                return;

            foreach (var item in quesPanel_List)
            {
                item.SetActive(false);
            }

            singleChoicePanel.SetActive(true);
            singleChoicePanel.GetComponent<ScrollRect>().verticalScrollbar.value = 1;
        }

        void onMultipleToggleChanged(bool isOn)
        {
            if (!isOn)
                return;

            foreach (var item in quesPanel_List)
            {
                item.SetActive(false);
            }

            multipleChoicePanel.SetActive(true);
            multipleChoicePanel.GetComponent<ScrollRect>().verticalScrollbar.value = 1;
        }

        void OnTrueFalseToggleChanged(bool isOn)
        {
            if (!isOn)
                return;

            foreach (var item in quesPanel_List)
            {
                item.SetActive(false);
            }

            trueFalsePanel.SetActive(true);
            trueFalsePanel.GetComponent<ScrollRect>().verticalScrollbar.value = 1;
        }

        void OnBlankToggleChanged(bool isOn)
        {
            if (!isOn)
                return;

            foreach (var item in quesPanel_List)
            {
                item.SetActive(false);
            }

            blankPanel.SetActive(true);
            blankPanel.GetComponent<ScrollRect>().verticalScrollbar.value = 1;
        }

        void OnShortAnswerToggleChanged(bool isOn)
        {
            if (!isOn)
                return;

            foreach (var item in quesPanel_List)
            {
                item.SetActive(false);
            }

            shortAnswerPanel.SetActive(true);
            shortAnswerPanel.GetComponent<ScrollRect>().verticalScrollbar.value = 1;
        }

        // 判断当前做题的进度
        void JudgeSubjectDoneProgress()
        {
            if (singleChoicePanel.activeInHierarchy)
            {
                singleDone_Num = 0;
                for (int i = 0; i < allSingle_List.Count; i++)
                {
                    if (allSingle_List[i].IsDone())
                        singleDone_Num++;
                }
                single_Toggle.GetComponentInChildren<Text>().text = string.Format("单选题({0}/{1})", singleDone_Num.ToString(), quesDataModel.Single_Num.Value.ToString());
            }

            if (multipleChoicePanel.activeInHierarchy)
            {
                multipleDone_Num = 0;
                for (int i = 0; i < allMultiple_List.Count; i++)
                {
                    if (allMultiple_List[i].IsDone())
                        multipleDone_Num++;
                }
                multiple_Toggle.GetComponentInChildren<Text>().text = string.Format("多选题({0}/{1})", multipleDone_Num.ToString(), quesDataModel.Multiple_Num.Value.ToString());
            }

            if (trueFalsePanel.activeInHierarchy)
            {
                trueFalseDone_Num = 0;
                for (int i = 0; i < allTrueFalse_List.Count; i++)
                {
                    if (allTrueFalse_List[i].IsDone())
                        trueFalseDone_Num++;
                }
                trueFalse_Toggle.GetComponentInChildren<Text>().text = string.Format("判断题({0}/{1})", trueFalseDone_Num.ToString(), quesDataModel.TrueFalse_Num.Value.ToString());
            }

            if (blankPanel.activeInHierarchy)
            {
                blankDone_Num = 0;
                for (int i = 0; i < allBlank_List.Count; i++)
                {
                    if (allBlank_List[i].IsDone())
                        blankDone_Num++;
                }
                blank_Toggle.GetComponentInChildren<Text>().text = string.Format("填空题({0}/{1})", blankDone_Num.ToString(), quesDataModel.Blank_Num.Value.ToString());
            }

            if (shortAnswerPanel.activeInHierarchy)
            {
                shortAnswer_Num = 0;
                for (int i = 0; i < allShortAnswer_List.Count; i++)
                {
                    if (allShortAnswer_List[i].IsDone())
                        shortAnswer_Num++;
                }
                shortAnswer_Toggle.GetComponentInChildren<Text>().text = string.Format("简答题({0}/{1})", shortAnswer_Num.ToString(), quesDataModel.ShortAnswer_Num.Value.ToString());
            }

            if (singleDone_Num == quesDataModel.Single_Num.Value
                && multipleDone_Num == quesDataModel.Multiple_Num.Value
                && trueFalseDone_Num == quesDataModel.TrueFalse_Num.Value
                && blankDone_Num == quesDataModel.Blank_Num.Value
                && shortAnswer_Num == quesDataModel.ShortAnswer_Num.Value)
                isAllQuesComplete = true;
            else
                isAllQuesComplete = false;
        }

        // 点击提交按钮
        void OnClickSubmitBtn()
        {
            if (!isAllQuesComplete)
            {
                quizTipsPanel.ShowTipsPanel("还有题目没有做完！", "继续", "放弃", TipType.Continue);
                return;
            }
            else
            {
                int single_rightNum = 0;

                for (int i = 0; i < allSingle_List.Count; i++)
                {
                    if (allSingle_List[i].IsCorrect())
                        single_rightNum++;
                }

                int multiple_rightNum = 0;

                for (int i = 0; i < allMultiple_List.Count; i++)
                {
                    if (allMultiple_List[i].IsCorrect())
                        multiple_rightNum++;
                }

                int trueFalse_rightNum = 0;

                for (int i = 0; i < allTrueFalse_List.Count; i++)
                {
                    if (!allTrueFalse_List[i].IsCorrect())
                        trueFalse_rightNum++;
                }

                int blank_rightNum = 0;

                for (int i = 0; i < allBlank_List.Count; i++)
                {
                    if (!allBlank_List[i].IsCorrect())
                        blank_rightNum++;
                }

                int shortAnswer_rightNum = 0;

                for (int i = 0; i < allShortAnswer_List.Count; i++)
                {
                    if (!allShortAnswer_List[i].IsCorrect())
                        shortAnswer_rightNum++;
                }

                // 最终得分
                int totalScore = quesDataModel.QuizData.Value.SingleChoice_Score * single_rightNum
                      + quesDataModel.QuizData.Value.MultipleChoice_Score * multiple_rightNum
                      + quesDataModel.QuizData.Value.TrueFalse_Score * trueFalse_rightNum
                      + quesDataModel.QuizData.Value.Blank_Score * blank_rightNum
                      + quesDataModel.QuizData.Value.ShortAnswer_Score * shortAnswer_rightNum;

                if (totalScore == quesDataModel.TotalScore.Value)
                {
                    quizTipsPanel.ShowTipsPanel("本次考试得分为：" + totalScore + "\n您获得了满分!", "", "结束", TipType.FullScore);
                }
                else
                {
                    quizTipsPanel.ShowTipsPanel("本次考试得分为：" + totalScore + "\n是否查看错题?", "是", "否", TipType.NotFullScore);
                }
            }
        }

        // 展示错题
        void OnShowWrongQuesItem()
        {
            tipsPanel_Go.SetActive(false);
            Submit_Btn.gameObject.SetActive(false);

            singleChoiceGrid.cellSize = new Vector2(1000, 620);
            multipleChoiceGrid.cellSize = new Vector2(1000, 620);
            trueFalseGrid.cellSize = new Vector2(1000, 280);
            blankGrid.cellSize = new Vector2(1000, 280);
            shortAnswerGrid.cellSize = new Vector2(1000, 430);

            for (int i = 0; i < allSingle_List.Count; i++)
            {
                if (allSingle_List[i].IsCorrect())
                {
                    allSingle_List[i].gameObject.SetActive(false);
                }
                else
                {
                    allSingle_List[i].analysis_Txt.gameObject.SetActive(true);
                    allSingle_List[i].HideToggle();
                }
            }

            for (int i = 0; i < allMultiple_List.Count; i++)
            {
                if (allMultiple_List[i].IsCorrect())
                {
                    allMultiple_List[i].gameObject.SetActive(false);
                }
                else
                {
                    allMultiple_List[i].analysis_Txt.gameObject.SetActive(true);
                    allMultiple_List[i].HideToggle();
                }
            }

            for (int i = 0; i < allTrueFalse_List.Count; i++)
            {
                if (allTrueFalse_List[i].IsCorrect())
                {
                    allTrueFalse_List[i].gameObject.SetActive(false);
                }
                else
                {
                    allTrueFalse_List[i].analysis_Txt.gameObject.SetActive(true);
                    allTrueFalse_List[i].HideToggle();
                }
            }

            for (int i = 0; i < allBlank_List.Count; i++)
            {
                if (allBlank_List[i].IsCorrect())
                {
                    allBlank_List[i].gameObject.SetActive(false);
                }
                else
                {
                    allBlank_List[i].analysis_Txt.gameObject.SetActive(true);
                    allBlank_List[i].DisableInput();
                }
            }

            for (int i = 0; i < allShortAnswer_List.Count; i++)
            {
                if (allShortAnswer_List[i].IsCorrect())
                {
                    allShortAnswer_List[i].gameObject.SetActive(false);
                }
                else
                {
                    allShortAnswer_List[i].analysis_Txt.gameObject.SetActive(true);
                    allShortAnswer_List[i].DisableInput();
                }
            }
        }
    }
}